package com.maya.medicalwastes.httpNet.interceptor;

import android.content.Context;

import com.maya.medicalwastes.httpNet.common.SharedPreferencesConstant;
import com.maya.medicalwastes.util.PrefUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Response;

/**
 * @description 在okhttp的返回的数据头上获取cookie并存储到缓存中的拦截器
 * @user gzl
 * @date 2017/5/19
 * @time 14:47
 */
public class ReceivedCookiesInterceptor implements Interceptor {
    protected static ReceivedCookiesInterceptor instance;
    protected static Context mContext;
    private static String mHttpUrl;

    public static ReceivedCookiesInterceptor getInstance(Context context, String url) {
        if (instance == null) {
            synchronized (ReceivedCookiesInterceptor.class) {
                if (instance == null) {
                    instance = new ReceivedCookiesInterceptor();
                }
            }
        }
        if (mContext == null) {
            mContext = context;
        }
        if (mHttpUrl == null) {
            mHttpUrl = url;
        }
        return instance;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Response originalResponse = chain.proceed(chain.request());
        if (!originalResponse.headers("Set-Cookie").isEmpty()) {
            for (String header : originalResponse.headers("Set-Cookie")) {
                if (header.toLowerCase().contains("session"))
                    PrefUtils.putString(mContext, SharedPreferencesConstant.SESSION, header);
                if (header.toLowerCase().contains("rememberme") && !header.toLowerCase().contains("deleteme")) {
                    try {
                        PrefUtils.putString(mContext, SharedPreferencesConstant.REMEMBER_ME, header);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return originalResponse;
    }
}
